<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>二分查找</title>
  </head>
  <body>
    <script>
      var search = function (num, target) {
        let low = 0,
          high = num.length - 1;
        while (low <= high) {
          const mid = Math.floor((high - low) / 2) + low;
          const n = num[mid];
          if (n === target) {
            return mid;
          } else if (n > target) {
            high = mid - 1;
          } else {
            low = mid + 1;
          }
        }
        return -1;
      };
      var num = [-1, 0, 3, 5, 9, 12],
        target = 9;
      console.log(search(num, target));
    </script>
  </body>
</html>
